// packageFactory/pages/factory/factory-detail.js
import UserService from '../../../service/UserService.js';
import OrderService from '../../../service/OrderService.js';
import CommonService from '../../../service/CommonService.js'
import { calcRate, throttle } from '../../../utils/util.js';
import { calendar } from '../../../utils/format/DateFormat';
import { createRandom, createSign } from '../../../utils/wxutil.js';

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user:{},
    evaluates:[],
    evaluateCount: 0,
    id:null,
    orderId: null,
    isFavorite: false,
    showModal: false,
    isUpdateMoney: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const _ = this;
    const { id, orderId } = options;
    _.userService = new UserService();
    _.orderService = new OrderService();
    _.commonService = new CommonService();
    _.browse(id);
    if(orderId){
      _.setData({ id, orderId });
      //查询该工厂是否被收藏
      _.isFavorite(id);
      _.getOrder(orderId);
    }else{
      _.setData({ id })
    }
    
    
    _.userService.getUserById(id).then(function (res) {
      if (res.status == 0) {
        _.setData({ user: res.data })
      }
    })
    _.userService.evaluates(id).then(function(res){
      if (res.status == 0) {
        _.setData({ evaluates: res.data.list,evaluateCount: res.data.count })
      }
    })
  },

  

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    const _ = this;
    const {id} = _.data;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    const redirectUrl = encodeURIComponent('/packageFactory/pages/factory/factory-detail?id=' + id)


    return {
      title: '分享工厂',
      path: `/pages/welcome/launch?redirectUrl=${redirectUrl}`,
      //imageUrl: app.globalData.user.cardImg,
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          const { shareScore } = app.globalData.setting;
          _.commonService.active(1).then(function (res) {
            if (res.status == 0) {
              wx.showModal({
                title: '谢谢分享',
                content: `恭喜你获得${shareScore}枚救兵勋章`,
                showCancel: false,
                confirmText: '知道了',
                confirmColor: '#0f9bc1'
              })
            }
          });
        }
      },
    }
  },
  onShare: function(){
    const _ = this;
    wx.showShareMenu({
      withShareTicket: true,
      success: function () {
        console.log('aaaa')
      }
    })
  },
  /**浏览工厂 */
  browse: function(id){
    const _ = this;
    setTimeout(function(){
      _.userService.browse(id);
    }, 3000);
  },
  isFavorite: function(id){
    const _ = this;
    _.userService.isFavoriteFactory(id).then(res => {
      if (res.status === 0) {
        _.setData({ isFavorite: res.data });
      }
    })
  },
  getOrder: function (orderId){
    const _ = this;
    _.orderService.getOrderById(orderId).then(res => {
      if (res.status === 0) {
        res.data.createTime = calendar(res.data.createTime);
        _.setData({ order: res.data, budgetMoney: res.data.budgetMoney });
      }
    })
  },
  /**打电话 */
  callPhone: function(){
    const _ = this;
    throttle(function(){
      const { activeScore } = app.globalData.user;
      const { user } = _.data;
      if (activeScore && activeScore > 1) {
        wx.showModal({
          title: '温馨提示',
          content: '拨打电话将扣去2枚救兵勋章',
          cancelText: '下次拨打',
          confirmText: '知道了',
          confirmColor: '#00accd',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.makePhoneCall({
                phoneNumber: user.phone //仅为示例，并非真实的电话号码
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      } else {
        wx.showModal({
          title: '温馨提示',
          content: '救兵勋章不足，递名片、发红包、分享、写评论可获得',
          showCancel: false,
          confirmText: '知道了',
          confirmColor: '#00accd'
        })
      }
    },1000)();
    
  },
  /**收藏工厂 */
  doFavorite:function(){
    const _ = this;
    throttle(function(){
      const { id, isFavorite } = _.data;
      if (isFavorite) return true;
      _.userService.favoriteFactory(id).then(res => {
        if (res.status === 0) {
          _.setData({ isFavorite: true });
          wx.showToast({
            title: '收藏成功',
            icon: 'success',
            duration: 2000
          })
        }
      })
    },1000)();
    
  },
  doCheckedFactory:function(){
    const _ = this;
    throttle(function(){
      _.orderService.update(_.getUpdateOrder()).then(res => {
        if (res.status === 0) {
          _.setData({ showModal: true });
        }
      })
    },1000)();
    
  },
  /**关闭保证金弹出框 */
  onCancel:function(){
    const _ = this;
    throttle(function () {
      _.setData({ showModal: false });
    },1000)();
  },
  getUpdateOrder: function(){
    const _ = this;
    const { order, budgetMoney, user } = this.data;
    const qualityMoney = budgetMoney * 0.05;
    const cashMoney = budgetMoney * calcRate(user.creditScore) - qualityMoney;
    const param = {
      id: order.id,
      factoryId: user.id,
      budgetMoney,
      qualityMoney,
      cashMoney,
      remainMoney: qualityMoney + cashMoney
    }
    return param;
  },
  /**更新预算金额 */
  onUpdate:function(){
    const _ = this;
    throttle(function(){
      const { isUpdateMoney, order, budgetMoney } = _.data;
      if (isUpdateMoney) {
        _.orderService.update(_.getUpdateOrder()).then(res => {
          if (res.status === 0) {
            order.budgetMoney = budgetMoney;
            _.setData({ order, isUpdateMoney: false })
          }
        })
      } else {
        _.setData({
          isUpdateMoney: true
        });
      }
    },1000)();
    
  },
  onBudgetMoney:function(e){
    const _ = this;
    throttle(function(){
      _.setData({ budgetMoney: e.detail.value })
    },1000)();
  },
  doPay:function(){
    const _ = this;
    throttle(function(){
      const { order } = _.data;
      const key = 'RESCUE20180712MEGOSKY888rescuems';
      _.orderService.unifiedorder(order.orderCode).then(function (result) {
        if (result.status == 0 && result.data.prepay_id) {
          const params = {
            appId: 'wxcadaf904d7fa0bf0',
            timeStamp: Date.parse(new Date()) + '',
            nonceStr: createRandom(),
            package: 'prepay_id=' + result.data.prepay_id,
            signType: 'MD5'
          };
          const sign = createSign(params, key);
          wx.requestPayment({
            'timeStamp': params.timeStamp,
            'nonceStr': params.nonceStr,
            'package': params.package,
            'signType': params.signType,
            'paySign': sign,
            'success': function (res) {
              if (res.errMsg == 'requestPayment:ok') {
                wx.showToast({
                  title: '支付成功',
                  icon: 'success',
                  duration: 2000
                })
                setTimeout(function () {
                  wx.navigateBack({
                    delta: 2
                  })
                }, 2000)
              }
            },
            'fail': function (res) {
              console.log('fail')
              wx.showToast({
                title: '支付失败',
                icon: 'none',
                duration: 2000
              });
              setTimeout(function () {
                wx.navigateBack({
                  delta: 2
                })
              }, 2000)
            }
          })
        }
      })
    },1000)();
  }
})